package apidocs;

import groovy.lang.Closure;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import play.mvc.Router;
import play.templates.FastTags;
import play.templates.GroovyTemplate;
import play.vfs.VirtualFile;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 页面所需的标签,放入此类
 * @author zhangzc@djcars.cn
 */
public class XTagForApi extends FastTags {

    private static final Map<String, String> hrefCache = new ConcurrentHashMap();
    private static ThreadLocal<SimpleDateFormat> fileSigFormat = new ThreadLocal();

    public static void _href(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine){
        if (!args.containsKey("arg") || args.get("arg") == null) {
            // do nothing
            return;
        }
        String action = (String) args.get("arg");
        try{

            VirtualFile file = Play.getVirtualFile(action);
            if(!file.exists()){
                Logger.warn("Can't find static file: %s", action);
                out.write(action);
                return;
            }
            String href = Router.reverseWithCheck(action, file, false);
            // search from local cache
            String fileSig = hrefCache.get(action);
            if(StringUtils.isEmpty(fileSig)){ // when not found
                SimpleDateFormat sdf = fileSigFormat.get();
                if(sdf == null){
                    sdf = new SimpleDateFormat("yyyyMMddHHmm");
                    fileSigFormat.set(sdf);
                }
                fileSig = sdf.format(new Date(file.lastModified()));
                // save to local cache
                hrefCache.put(action, fileSig);
            }
            out.write(href);
            if(StringUtils.contains(href, "?")){
                out.write("&t=");
            }else{
                out.write("?t=");
            }
            out.write(fileSig);
        }catch (Exception e){
            Logger.error(e, "Error in generating href: %s", action);
            out.write(action);
        }
    }



}
